package services;

import dao.*;
import models.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import play.db.jpa.JPAApi;
import utils.HashUtil;
import vo.UserInfo_C_Entity;

import javax.inject.Inject;
import javax.persistence.Query;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletionStage;

import static java.util.concurrent.CompletableFuture.supplyAsync;


/**
 * Provide JPA operations running inside of a thread pool sized to the connection pool
 */
public class

User_Repository_JPA implements User_Repository {

    private final JPAApi jpaApi;
    private final DatabaseExecutionContext executionContext;

    @Inject
    public User_Repository_JPA(JPAApi jpaApi, DatabaseExecutionContext executionContext) {
        this.jpaApi = jpaApi;
        this.executionContext = executionContext;
    }

    @Override
    public CompletionStage<UserInfo_C_Entity> isRegistered(String mobile, String password) {
        return supplyAsync(() -> {
            return jpaApi.withTransaction(entityManager -> {
                Query query = entityManager.createQuery("select new vo.UserInfo_C_Entity(u.fdUserId, r.fd_RoleID, u.fdUserName, u.fdImei, u.fdPasswordHash, u.fdDeptId, u.fdRegisterDate,u.fdLastLoginDate, u.fdToken, u.fdMobile, u.deleted, d.fdDeptName) from UserInfo_T_Entity u,UserInRole_T_Entity r, DeptInfo_T_Entity d where u.fdMobile = :mobile and u.fdDeptId = d.fdDeptId and u.fdUserId = r.fd_UserID", UserInfo_C_Entity.class).setParameter("mobile", mobile);
                UserInfo_C_Entity _user = new UserInfo_C_Entity();
                if (query.getResultList().size() > 0) {
                    _user = (UserInfo_C_Entity) query.getSingleResult();
                } else {
                    // 用户不存在等“异常”情况，仍然以User结构返回。异常处理在前台处理。
                    _user.setfd_UserID(0);
                }

                return _user;
            });
        }, executionContext);
    }

    @Override
    public CompletionStage<List<Object>> login(String mobile, String password, String IMEI) {
        return supplyAsync(() -> {
            return jpaApi.withTransaction(entityManager -> {
                List<UserInfo_T_Entity> resultList = null;
                List<UserInfo_C_Entity> resultList1 = null;
                UserInfo_C_Entity _user = new UserInfo_C_Entity();

                Query query = entityManager.createQuery("select new vo.UserInfo_C_Entity(u.fdUserId, r.fd_RoleID, u.fdUserName, u.fdImei, u.fdPasswordHash, u.fdDeptId, u.fdRegisterDate,u.fdLastLoginDate, u.fdToken, u.fdMobile, u.deleted, d.fdDeptName) from UserInfo_T_Entity u,UserInRole_T_Entity r, DeptInfo_T_Entity d where u.fdMobile = :mobile and u.fdDeptId = d.fdDeptId and u.fdUserId = r.fd_UserID", UserInfo_C_Entity.class).setParameter("mobile", mobile);
//                    resultList = query.setParameter("mobile", mobile).getResultList();


                if ((StringUtils.isEmpty(mobile)) || StringUtils.isEmpty(password)) {
                    return utils.StringToList.StringtoList("请输入用户名和密码");
                }
                if (StringUtils.isNotBlank(mobile)) {

                    Query query1 = entityManager.createQuery("select u from  UserInfo_T_Entity u where u.fdMobile=:mobile", UserInfo_T_Entity.class);


                    resultList = query1.setParameter("mobile", mobile).getResultList();



                }
                if (CollectionUtils.isEmpty(resultList)) {
                    return utils.StringToList.StringtoList("该用户未注册");
                }
                UserInfo_T_Entity userInfo_T_Entity = resultList.get(0);
                if (!HashUtil.genMixedHash(password).equals(
                        userInfo_T_Entity.getFdPasswordHash())) {
                    return utils.StringToList.StringtoList("用户名或密码错误！");
                }else {
                    _user = (UserInfo_C_Entity) query.getSingleResult();
                }
                String id = UUID.randomUUID().toString();
                userInfo_T_Entity.setFdToken(id);
                userInfo_T_Entity.setFdLastLoginDate(new Timestamp(new Date().getTime()).toString());

                if (!IMEI.equals("530330EB-3185-4D45-B031-5C4ECC1936E6") && !IMEI.equals("352562074120331,352563074120339") && !IMEI.equals("D634300E-179F-446D-9399-777921A77A1C") && !IMEI.equals("530330EB-3185-4D45-B031-5C4ECC1936E6") && !IMEI.equals("8CDBEC0C-7E01-431D-AABC-584A80E17649") && !IMEI.equals("530330EB-3185-4D45-B031-5C4ECC1936E6") && !mobile.equals("13590048001") && !mobile.equals("13311609883") && !mobile.equals("18016098756") && !mobile.equals("15816063908")&& !mobile.equals("13761121857")&& !mobile.equals("18825077720")) {
                    if (StringUtils.isNotBlank(userInfo_T_Entity.getFdImei())) {

                        Query queryImei = entityManager.createQuery("select u from  UserInfo_T_Entity u where u.fdMobile=:mobile and u.fdImei=:IMEI", UserInfo_T_Entity.class);
                        List<UserInfo_T_Entity> resultListI = queryImei.setParameter("mobile", mobile).setParameter("IMEI", IMEI).getResultList();
                        if (CollectionUtils.isEmpty(resultListI)) {
                            return utils.StringToList.StringtoList("请在绑定该手机号码的手机登陆");
                        }
                    } else {

                        userInfo_T_Entity.setFdImei(IMEI);
                    }

                }
                LoginLog_T_Entity  loginLog_T_Entity= new  LoginLog_T_Entity();
                loginLog_T_Entity.setFdImei(IMEI);
                loginLog_T_Entity.setFdLoginTime(new Timestamp(System.currentTimeMillis()));
                loginLog_T_Entity.setFdPhoneNumber(mobile);
                entityManager.persist(loginLog_T_Entity);
                // TODO: 2016/9/12 set cache
                // 手动提交（框架层面在HTTP返回前会自动提交，但由于这里需要成功后才更新缓存）
                entityManager.flush();
                    List<Object> objectList = new ArrayList<Object>();
                    objectList.add(_user);

                    return objectList;


            });
        }, executionContext);
    }


    @Override
    public CompletionStage<Object> logout(String fdMobile) {
        return supplyAsync(() -> {
            return jpaApi.withTransaction(entityManager -> {

               Query queryOut = entityManager.createQuery("select u from  UserInfo_T_Entity u where u.fdMobile=:mobile ", UserInfo_T_Entity.class);
                List<UserInfo_T_Entity> resultList = queryOut.setParameter("mobile", fdMobile).getResultList();
                resultList.get(0).setFdToken("");


                  return "成功退出";
            });
        }, executionContext);
    }

    @Override
    public CompletionStage<List<UserInfo_C_Entity>> getUserList() {
        return supplyAsync(() -> {
            return jpaApi.withTransaction(entityManager -> {
                return entityManager.createQuery("select new vo.UserInfo_C_Entity(u.fdUserId, r.fd_RoleID, u.fdUserName, u.fdImei, u.fdPasswordHash, u.fdDeptId, u.fdRegisterDate,u.fdLastLoginDate, u.fdToken, u.fdMobile, u.deleted, d.fdDeptName) from UserInfo_T_Entity u,UserInRole_T_Entity r, DeptInfo_T_Entity d where u.fdUserId = r.fd_UserID and u.fdDeptId = d.fdDeptId", UserInfo_C_Entity.class).getResultList();
            });
        }, executionContext);
    }



    public CompletionStage<Object> CreateUser(String type, String fdUserName, String fdMobile,String fdDeptId) {
        return supplyAsync(() -> {
            return jpaApi.withTransaction(entityManager -> {


                if (type == null || fdUserName == null || fdMobile == null || fdDeptId == null) {
                    return "请正确填写基本信息";
                }
                Query query = entityManager.createQuery("select u from UserInfo_T_Entity u where u.fdUserName = :fdUserName", UserInfo_T_Entity.class).setParameter("fdUserName", fdUserName);
                if(query.getResultList().size() > 0)
                {
                    return "该用户已存在";
                }
                Query query1 = entityManager.createQuery("select u from UserInfo_T_Entity u where u.fdMobile = :fdMobile", UserInfo_T_Entity.class).setParameter("fdMobile", fdMobile);
                if(query1.getResultList().size() > 0)
                {
                    return "该手机号已存在";
                }
                UserInfo_T_Entity user = new UserInfo_T_Entity();
                user.setFdDeptId(Integer.valueOf(fdDeptId));
                user.setFdUserName(fdUserName);
                user.setFdPasswordHash(HashUtil.genMixedHash("888888"));
                user.setFdMobile(fdMobile);
                user.setFdRegisterDate(new Timestamp(System.currentTimeMillis()).toString());
                user.setFdLastLoginDate(new Timestamp(System.currentTimeMillis()).toString());
                user.setFdImei("");
                user.setFdToken("");
                user.setFd_MemberNo("");
                entityManager.persist(user);

                // 关联角色信息
                UserInRole_T_Entity userInRoleEntity = new UserInRole_T_Entity();
                userInRoleEntity.setFd_ModifiedDate(new Timestamp(new Date().getTime()).toString());
                userInRoleEntity.setFd_RoleID(Integer.valueOf(type));
                userInRoleEntity.setFd_UserID(user.getFdUserId());
                entityManager.persist(userInRoleEntity);


                return "添加成功";
            });
        }, executionContext);
    }

    @Override
    public CompletionStage<String> ModifyPassword(String phoneNumber ,String oldPassword,String newPassword) {
        return supplyAsync(() -> {
            return jpaApi.withTransaction(entityManager -> {

                List<UserInfo_T_Entity> query = entityManager.createQuery("select u from UserInfo_T_Entity u where u.fdMobile = :phoneNumber and u.fdPasswordHash =:oldPassword", UserInfo_T_Entity.class).setParameter("phoneNumber", phoneNumber).setParameter("oldPassword",HashUtil.genMixedHash(oldPassword)).getResultList();
                   if(CollectionUtils.isEmpty(query)){

                       return "账号或密码错误";
                   }else{

                       for(UserInfo_T_Entity entity: query){
                           entity.setFdPasswordHash(HashUtil.genMixedHash(newPassword));
                       }

                       return "修改成功";
                   }


            });
        }, executionContext);
    }

//    public CompletionStage<String> CreateUser(String fdUserName, String fdImei, String fdDeptId, String fdRegisterDate, String fdLastLoginDate, String fdToken, String fdMobile, String deleted, String fd_MemberNo)
//    {
//        return supplyAsync(() -> {
//            return jpaApi.withTransaction(entityManager -> {
//                // 插入一个原生SQL的测试,调用了SQLServer的自定义函数.
//                String strSql = "insert into t_UserInfo([fd_UserName], [fd_IMEI], [fd_PasswordHash], [fd_DeptId], [fd_RegisterDate], [fd_LastLoginDate], [fd_Token], [fd_Mobile], [deleted], [fd_MemberNo])values('"+ fdUserName +"','"
//                        + fdImei +"','bdd747317910dc3c6657bdf1f5843c09','"
//                        + fdDeptId +"','"
//                        + fdRegisterDate +"','"
//                        + fdLastLoginDate+"','"
//                        + fdToken +"',"
//                        + fdMobile +",'0','"
//                        + fd_MemberNo +"')";
//                entityManager.createNativeQuery(strSql).executeUpdate();
//                return "";
//            });
//        }, executionContext);
//    }



}